//dll ws2_32.dll
#include <winsock2.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>

SOCKET sock=0;

void test(void* v){
    char buff[10240];
    int len;
    char *exit="exit";
    struct sockaddr_in target;
    int slen=sizeof(struct sockaddr);
    while(sock){
        len=recvfrom(sock,buff,sizeof(buff),0,(struct sockaddr *)&target,&slen);
        if(len==-1)continue;
        sendto(sock,"ok",2,0,(const struct sockaddr *)&target,sizeof(target));
        printf("recv:%d %s\r\n",len,&buff);
        if(*((int*)exit)==(*(int*)buff))
            break;
        
        Sleep(0);
    }
    printf("thread end\r\n");
}
HANDLE h1;

int getIPs(int* ips,int *count){
    char buff[64];
    int i;
    struct sockaddr_in sa;
    int c=0;
    gethostname(&buff,sizeof(buff));
    struct hostent* phost=gethostbyname(&buff);
    for(i=0;phost->h_addr_list[i];i++){
        *ips++=*((int*)phost->h_addr_list[i]);
        c++;
    }
    *count=c;
}

main(){
    WSADATA data;
    
    struct sockaddr_in si;
    struct sockaddr_in st;
    int t=time(0);
    printf("time:%d",time(0)-t);
    printf("WSAStartup:%d\r\n",WSAStartup(MAKEWORD(2,2),&data));

    int iplist[16];
    int ipcount=16;
    getIPs(&iplist,&ipcount);
    int i;
    for(i=0;i<ipcount;i++){
        iplist[i]|=0xff000000;
        printf("Address:%s\n",inet_ntoa((struct in_addr)iplist[i]));
    }

    si.sin_family=AF_INET;
    si.sin_port=htons(52);
    si.sin_addr.S_un.S_addr=ADDR_ANY;

    st.sin_family=AF_INET;
    st.sin_port=htons(51);
    st.sin_addr.S_un.S_addr=iplist[1]|0xff000000;

    
    //sock=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED);
    sock=WSASocket(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED);
    i=1;
    ioctlsocket(sock,FIONBIO,&i);
    bind(sock,(const struct sockaddr *)&si,sizeof(si));
    //listen(sock,5);
    sendto(sock,"test\r\n",6,0,(const struct sockaddr *)&st,sizeof(st));
    //connect(sock,)

    //bind(sock,(const struct sockaddr *)&si,sizeof(si));
    h1=_beginthread(test,0,NULL);
    WaitForSingleObject(h1,INFINITE);
    printf("Socket:%x\r\n",sock);
    if(sock)
        closesocket(sock);
    WSACleanup();
}